<template>
	<view class="after_sale">
		<!-- 商品信息 -->
		<view class="submit_rder_info_goods">
			<view class="submit_rder_info_goods_body">
				<image :src="fromValue.goodsImages" class="submit_rder_info_goods_body_left"></image>
				<view class="submit_rder_info_goods_body_right">
					<view class="submit_rder_info_goods_body_right_top">
						<view class="submit_rder_info_goods_body_right_top_1">
							{{fromValue?.goodsName}}
						</view>
						<view class="submit_rder_info_goods_body_right_top_2">
							<text class="submit_rder_info_goods_body_right_top_2_left"
								v-if="fromValue?.specifications">{{fromValue?.specifications}}</text>
							<text class="submit_rder_info_goods_body_right_top_2_right">x1</text>
						</view>
					</view>
					<view class="submit_rder_info_goods_body_right_btm">
						<view class="submit_rder_info_goods_body_right_btm_price goods_price18">
							<text>￥</text>{{fromValue?.totalPrice}}
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 退货类型 -->
		<view class="after_sale_type">
			<view class="after_sale_type_top">
				<text class="after_sale_type_top_1">我要{{fromValue?.returnTypeText}}</text>
				<text class="after_sale_type_top_2"
					v-if="fromValue?.applyRefundDateText">{{fromValue?.applyRefundDateText}}</text>
			</view>
			<view class="after_sale_type_btm">
				{{fromValue?.returnType === '1'?'没有收到货只需退款':'收到货进行退款退货'}}
			</view>
		</view>
		<!-- 第二次申请 -->
		<view class="after_sale_type" v-if="fromValue?.id">
			<view class="after_sale_type_top">
				<text class="after_sale_type_top_1">拒绝原因</text>
			</view>
			<view class="after_sale_type_btm">
				<text style="color: #ff0000;font-size: 30rpx;">{{fromValue?.scheduleExplain}}</text>
			</view>
		</view>
		<!-- 售后输入 -->
		<view class="return_logistics">
			<view class="after_sale_form custom_form">
				<view class="custom_form_body">
					<view class="custom_form_body_item">
						<text><text>*</text>货物状态</text>
						<text
							style="text-align: right;">{{fromValue?.returnType === '1'?'未收货':'已收货'}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</text>
					</view>
					<view class="custom_form_body_item" @click="handleCause()">
						<text><text>*</text>退款原因</text>
						<view class="custom_form_body_item_right">
							<text v-if="fromValue?.orderReturnCauseText">{{fromValue?.orderReturnCauseText}}</text>
							<text v-else class="placeholder">请选择</text>&nbsp;
							<u-icon name="arrow-right" color="#444444" size="12"></u-icon>
						</view>
					</view>
					<view class="custom_form_body_item" :style="{borderBottom:isShow?'':'1px solid #E6E6E6'}">
						<text>退款金额</text>
						<view class="custom_form_body_item_right" @click="isShow = !isShow">
							<view class="goods_price20"><text>￥</text>{{fromValue.applyPrice}}</view>&nbsp;
							<u-icon name="arrow-up" v-if="isShow" color="#444444" size="12"></u-icon>
							<u-icon name="arrow-down" v-else color="#444444" size="12"></u-icon>
						</view>
					</view>
					<template v-if="isShow">
						<view class="custom_form_body_item_two">
							<text>商品金额</text>
							<view class="goods_price16"><text>￥</text>{{fromValue.totalPrice}}</view>
						</view>
						<view class="custom_form_body_item_two">
							<text>运费金额</text>
							<view class="goods_price16"><text>￥</text>{{fromValue.freightCharges}}</view>
						</view>
					</template>
					<view class="custom_form_body_item no_border">
						<text style="width: 300rpx;">补充描述和凭证</text>
					</view>
					<u-textarea maxlength="50" count placeholder="请输入退款缘由" border="none"
						v-model="fromValue.replenishCause"></u-textarea>
					<view class="custom_form_body_upload">
						<template v-if="fromValue.images">
							<view v-for="(item,index) in fromValue.images" :key="index"
								@click.stop="handlePreview(index)">
								<text @click.stop="handleDelImg(index)">×</text>
								<image :src="item"></image>
							</view>
						</template>
						<view v-if="fromValue.images?.length <= 5" @click="handleUpload">
							<image src="http://qianxueapplet.suoeryun.com/addimage.png">
							</image>
						</view>
					</view>
				</view>
				<!-- <view class="custom_form_btn" @click="handleSave">提交</view> -->
				<!--  退款原因选择-->
				<u-picker :show="isCause" :columns="columns" keyName="text" @confirm="handleCauseConfirm"
					@cancel="handleCauseCancel"></u-picker>
			</view>
		</view>
	</view>
	<view class="btm_btm safe_area">
		<view class="btm_btm_row">
			<button class="row_btn" @click="handleSave">提交</button>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, reactive, unref, getCurrentInstance } from 'vue';
	import config from '@/common/config';
	import { qxGoodsOrderQueryById, qxGoodsOrderReturnAdd, qxGoodsOrderReturnQueryById, resubmit } from '@/config/goodStuff.api';
	import { onLoad } from '@dcloudio/uni-app';
	import { getDictItemsByCode } from '@/config/sys.api';

	const { proxy } = getCurrentInstance();
	const isCause = ref(false);
	const columns = reactive([]);
	const isShow = ref(false);
	const fromValue = reactive({
		"id": "",
		"address": "",
		"addressLat": 0,
		"addressLng": 0,
		"applyNum": 0,
		"applyPrice": 0,
		"attributeId": "",
		"categoryId": "",
		"categoryName": "",
		"consignee": "",
		"finishTime": "",
		"goodsId": "",
		"goodsImages": "",
		"goodsName": "",
		"orderId": "",
		"izFinish": "",
		"location": "",
		"locationCode": "",
		"logisticCode": "",
		"orderNum": 0,
		"orderReturnCause": "",
		"orderReturnCauseText": "",
		"payAmount": 0,
		"phone": "",
		"phoneNumber": "",
		"prepayId": "",
		"replenishCause": "",
		"returnType": "",
		"returnTypeText": "",
		"scheduleId": "",
		"images": [],
		"sendBackReplenish": "",
		"shipperCode": "",
		"specifications": "",
		"totalPrice": 0,
		"unitPrice": 0,
		"applyRefundDateText": '',
		"applyRefundDate": '',
		"freightCharges": 0,
		"scheduleExplain": '',
	});

	onLoad(async (option) => {
		// 获取退货原因数据
		const result = await getDictItemsByCode({ dictCode: 'order_return_cause' });
		columns.push(result);
		// 第一次申请
		if (option?.orderId) {
			const res = await qxGoodsOrderQueryById({ id: option?.orderId });
			fromValue.attributeId = res?.attributeId;//	商品规格id
			fromValue.categoryId = res?.categoryId;//商品类别id
			fromValue.categoryName = res?.categoryName;//商品类别名称
			fromValue.goodsId = res?.goodsId;//商品ID
			fromValue.goodsImages = res?.goodsImages;//商品图片
			fromValue.goodsName = res?.goodsName;//商品名称
			fromValue.orderId = res?.id;//订单id
			fromValue.orderNum = res?.orderNum;//	数量
			fromValue.returnType = res?.orderStatus === '2' ? '1' : '2';//	操作类型 1退款、2退货退款
			fromValue.returnTypeText = res?.orderStatus === '2' ? '退款' : '退货退款';//	操作类型 1退款、2退货退款
			fromValue.specifications = res?.specifications;//	商品规格明文
			fromValue.totalPrice = res?.totalPrice;//		商品总价
			fromValue.unitPrice = res?.unitPrice;//	单价
			fromValue.applyPrice = res?.totalPrice + res?.freightCharges;//	申请退款金额
			fromValue.freightCharges = res?.freightCharges;//	邮费
			if (res?.applyRefundDate) {
				fromValue.applyRefundDateText = res?.applyRefundDate?.substring(0, 10)?.replace('-', '年')?.replace('-', '月') + '日';//	售后日期
			}
		}
		// 再次申请
		if (option?.id) {
			const res = await qxGoodsOrderReturnQueryById({ id: option?.id });
			fromValue.id = res?.id;//	退款售后id
			fromValue.returnType = res?.returnType;//	操作类型 1退款、2退货退款
			fromValue.returnTypeText = res?.orderStatus === '1' ? '退款' : '退货退款';//	操作类型 1退款、2退货退款
			fromValue.replenishCause = res?.replenishCause;//描述
			fromValue.images = res?.images ? res?.images?.split(',') : [];//图片
			fromValue.orderReturnCause = res?.orderReturnCause;//退款原因文本columns
			fromValue.scheduleExplain = res?.scheduleExplain;//退货原因
			const data = columns[0]?.filter(item => item?.value === res?.orderReturnCause);
			if (data?.length > 0) {
				fromValue.orderReturnCauseText = data[0]['text'];//退款原因文本
			}
		}
	})

	/**
	 * 打开退款原因
	 */
	function handleCause() {
		isCause.value = true;
	}

	/**
	 * 退款原因选择器 确认
	 */
	function handleCauseConfirm(arr) {
		console.log(arr.value[0], 'arr', arr?.value?.length);
		if (arr?.value?.length > 0) {
			fromValue.orderReturnCause = arr.value[0].value;
			fromValue.orderReturnCauseText = arr.value[0].text;
		}
		console.log(fromValue.orderReturnCause, 'orderReturnCause');
		isCause.value = false;
	}

	/**
	 * 退款原因选择器 取消
	 */
	function handleCauseCancel() {
		isCause.value = false;
	}

	/**
	 * 上传图片
	 */
	function handleUpload() {
		uni.chooseImage({
			count: 5 - fromValue.images?.length,
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				console.log(tempFilePaths, 'tempFilePaths');
				uni.showLoading();
				let count = 0;
				tempFilePaths?.forEach(item => {
					uni.uploadFile({
						url: config.baseUrl + '/sys/common/obsUpload', //仅为示例，非真实的接口地址
						filePath: item,
						name: 'file',
						header: {
							'X-Access-Token': unref(proxy['vuex_token'])
						},
						success: (uploadFileRes) => {
							count += 1;
							// commentInputRef.value.handleShow({ ...unref(record), imagesUrl: JSON.parse(uploadFileRes.data)?.message });
							fromValue.images.push(JSON.parse(uploadFileRes.data)?.message);
							uni.hideLoading();
						},
						fail() {
							uni.hideLoading();
							uni.showToast({
								icon: 'none',
								title: '接口异常！'
							})
						}
					});
				})
				setTimeout(_ => {
					if (count === tempFilePaths?.length) {
						uni.hideLoading();
					}
				}, 1000)
			},
			fail() {
				uni.hideLoading();
			}
		});
	}

	/**
	 * 提交
	 */
	async function handleSave() {
		if (fromValue.orderReturnCause === '') {
			return uni.showToast({
				icon: 'none',
				title: '请选择退款原因'
			})
		}
		uni.showModal({
			content: `是否提交${fromValue?.returnTypeText}申请`,
			success: async (res) => {
				if (res.confirm) {
					// 再次申请
					if (fromValue?.id) {
						await resubmit({ ...fromValue, images: fromValue?.images?.join(',') })
					} else {//第一次申请
						await qxGoodsOrderReturnAdd({ ...fromValue, images: fromValue?.images?.join(',') });
					}
					uni.showToast({
						icon: 'success',
						title: '提交成功',
						success() {
							uni.$u.route({
								type: 'back',
								delta: 2
							})
							uni.$emit('afterSale');
						}
					})
				}
			}
		})
	}


	/**
	 * 图片预览
	 */
	function handlePreview(index) {
		uni.previewImage({
			current: index,
			urls: fromValue.images,
		})
	}

	/**
	 * 删除图片
	 */
	function handleDelImg(index) {
		fromValue.images?.splice(index, 1);
	}
</script>

<style lang="scss" scoped>
	.after_sale {
		padding: 24rpx 24rpx 190rpx 24rpx;

		.submit_rder_info_goods_body {
			padding-top: 0;
		}

		// 售后类型
		.after_sale_type {
			.after_sale_type_top {
				display: flex;
				align-items: center;

				.after_sale_type_top_1 {
					font-size: 36rpx;
				}

				.after_sale_type_top_2 {
					display: inline-block;
					margin-left: 12rpx;
					border-radius: 162rpx;
					border: 2rpx solid #FF0101;
					color: #FF0101;
					padding: 8rpx 12rpx 0 12rpx;
					background-color: #FFE3E3;
					font-size: 32rpx;
				}
			}

			.after_sale_type_btm {
				padding-top: 10rpx;
				font-size: 24rpx;
				color: #8F8F8F;
			}
		}
	}

	.return_logistics {
		border-radius: 16rpx;
		height: auto;

		.after_sale_form {

			.custom_form_body {
				margin: 0;

				.custom_form_btn {
					margin-top: 66rpx;
				}
			}
		}
	}

	.custom_form_body_item_two {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 28rpx 20rpx;
		margin: 0;
		background-color: transparent;
		height: auto;
		line-height: auto;

		&:nth-child(5) {
			border-bottom: 1px solid #E6E6E6;
		}

		text {
			font-size: 32rpx;
		}

		.goods_price16 {
			color: #333333;
		}
	}

	.custom_form_body_item_right {
		.placeholder {
			font-size: 32rpx;
			font-weight: normal;
		}
	}
</style>